const { Sequelize } = require('sequelize');
const config = require('./config');

const env = process.env.NODE_ENV || 'development';
const dbConfig = config[env];

// 根据环境选择数据库配置
const sequelizeConfig = env === 'test'
  ? {
      dialect: 'sqlite',
      storage: ':memory:', // 使用内存数据库
      logging: false, // 禁用日志以提高测试性能
    }
  : {
      database: dbConfig.database,
      username: dbConfig.username,
      password: dbConfig.password,
      host: dbConfig.host,
      port: dbConfig.port,
      dialect: dbConfig.dialect,
      dialectOptions: dbConfig.dialectOptions,
      timezone: dbConfig.timezone,
      define: dbConfig.define,
      logging: dbConfig.logging,
    };

// 创建Sequelize实例
const sequelize = new Sequelize(sequelizeConfig);

// 测试数据库连接
const testConnection = async () => {
  try {
    await sequelize.authenticate();
    return true;
  } catch (error) {
    console.error('数据库连接失败:', error);
    return false;
  }
};

module.exports = {
  sequelize,
  testConnection,
};